package xueqiu

import (
	"fmt"
	"io/ioutil"

	"gitee.com/lenchu/stock-api-go/api"
	"gitee.com/lenchu/stock-api-go/utils"

	"github.com/tidwall/gjson"
)

const get_jj_url_template = "https://fund.xueqiu.com/dj/open/fund/growth/%s?day=30"

func (this *StockService) getJJ(xc *_XueqiuCode) *api.Stock {
	url := fmt.Sprintf(get_jj_url_template, xc.code)
	log.Println(url)
	resp, err := this.getWithRetry(url)
	if err != nil {
		return nil
	}
	byteBody, err := ioutil.ReadAll(resp.Body)
	strBody := string(byteBody)
	data := gjson.Get(strBody, "data")
	jjArray := data.Get("fund_nav_growth").Array()
	jjJson := jjArray[len(jjArray)-1]
	stock := api.Stock{
		Code:       xc.standardCode,
		Price:      jjJson.Get("nav").String(),
		UpdateTime: utils.StringToTime(jjJson.Get("date").String() + " 23:59:59"),
		Name:       resolveJjName(&data),
	}
	return &stock
}

func resolveJjName(data *gjson.Result) string {
	nameArr := data.Get("growth_lines.#.line_name").Array()
	return nameArr[len(nameArr)-1].String()
}
